package com.dsteiner.widgets.client.event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class EventManagerImpl implements EventManager{
	
	private static EventManagerImpl instance;

	public static EventManagerImpl getInstance() {
		if(instance == null){
			instance = new EventManagerImpl();
		}
		return instance;
	}

	private Map listeners = new HashMap();
	private Map<Class<? extends Event>, Event> eventMap = new HashMap<Class<? extends Event>, Event>();

	public void fireEvent(Event event) {
		eventMap.put(event.getClass(), event);
		Class<? extends Event> class1 = event.getClass();
		List list = (List) listeners.get(class1);
		if(list != null){
			List eventList = new ArrayList();
			eventList.addAll(list);
			for (Iterator iterator = eventList.iterator(); iterator.hasNext();) {
				EventListener listener = (EventListener) iterator.next();
				listener.onEvent(event);
			}
		}
	}

	@SuppressWarnings("unchecked")
	public  <T extends Event> T getEvent(Class<T> eventClass){
		return (T) eventMap.get(eventClass);
	}
	
	public void registerListener(Class eventClassname, EventListener listener){
		List list = (List) listeners.get(eventClassname);
		if(list == null)
			list = new ArrayList();
		list.add(listener);
		listeners.put(eventClassname, list);
	}

	public void clearListeners() {
		listeners.clear();
	}

	public void removeListener(Class eventClassname, EventListener listener) {
		List list = (List) listeners.get(eventClassname);
		if(list == null)
			return;
		list.remove(listener);
		listeners.put(eventClassname, list);
	}
	
}
